SRCROOT=.

CPP    = g++  
CC     = gcc
AR     = ar -rc

CPPSHARE = $(CPP) -fPIC -shared -O2 -pipe -o
CSHARE   = $(CC) -fPIC -shared -O2 -pipe -o

ifeq ($v,release)
CFLAGS = -c -O2 $(INCLS) -fPIC -DLINUX -pipe
else
CFLAGS = -c -g $(INCLS) -fPIC -DLINUX -pipe
endif

CPPCOMPI = $(CPP) $(CFLAGS) 
CCCOMPI  = $(CC) $(CFLAGS) 

STATICLIBPATH  = $(SRCROOT)/lib
DYNAMICLIBPATH = $(SRCROOT)/solib

INCLS = -I$(SRCROOT)/include
LIBS  = -L$(STATICLIBPATH)
LIBS  += -lpthread

OBJS  = lws_utils.o lws_triedict.o lws_wordgraph.o lws_basicseg.o \
	lws_hmm.o lws_recog.o lws_postag.o lws_segment.o lws_segger.o
PROGS = liblightwords.a liblightwords.so
TOOLS = trainword makedict expandict trainhmm
TEST  = test_basicseg test_segger

all: $(PROGS)
tool: $(TOOLS)
test: $(TEST)

liblightwords.a: $(OBJS)
	@( \
		echo -n "archieving $@ ..."; \
		$(AR) $(STATICLIBPATH)/$@ $+; \
		if [ $$? -ne 0 ]; then \
		exit 1; \
		else \
		echo "OK"; \
		fi \
	 )

liblightwords.so: $(OBJS) 
	@( \
		echo -n "archieving $@ ..."; \
		$(CPPSHARE) $(DYNAMICLIBPATH)/$@ $+; \
		if [ $$? -ne 0 ]; then \
		exit 1; \
		else \
		echo "OK"; \
		fi \
	 )

trainword: lws_utils.o lws_triedict.o trainword.o
	$(CPP) -o $@ $+

makedict: lws_utils.o lws_triedict.o makedict.o
	$(CPP) -o $@ $+

expandict: lws_utils.o lws_triedict.o expandict.o
	$(CPP) -o $@ $+

trainhmm: lws_utils.o lws_hmm.o trainhmm.o
	$(CPP) -o $@ $+

test_basicseg: $(OBJS) test_basicseg.o
	$(CPP) -o $@ $+

test_segger: $(OBJS) test_segger.o
	$(CPP) -o $@ $+

clean:
	rm -f *.o $(PROGS) $(TOOLS) $(TEST) $(STATICLIBPATH)/*.a $(DYNAMICLIBPATH)/*.so 

##define the cpp file compile rule
.cpp.o:
	@( \
		echo -n "compiling $< ... "; \
		$(CPPCOMPI)  $< 2>./.err.txt; \
		if [ $$? -ne 0 ];then \
		echo "Failed"; \
		cat ./.err.txt; \
		rm -f ./.err.txt; \
		exit 1; \
		else \
		rm -f ./.err.txt; \
		echo "OK"; \
		fi \
	 )

.c.o:
	@( \
		echo -n "compiling $< ... "; \
		$(CCCOMPI)  $< 2>./.err.txt; \
		if [ $$? -ne 0 ];then \
		echo "Failed"; \
		cat ./.err.txt; \
		rm -f ./.err.txt; \
		exit 1; \
		else \
		rm -f ./.err.txt; \
		echo "OK"; \
		fi \
	 )
